package com.group1.realtime.app;


import com.group1.realtime.util.FlinkSourceUtil;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.runtime.state.storage.JobManagerCheckpointStorage;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;

import java.util.HashMap;
import java.util.Map;

public abstract class BaseAppV2 {



    protected abstract void handle(StreamExecutionEnvironment env, HashMap<String, DataStreamSource<String>> stream);



    public  void init(int port, int parallelism, String groupIdAndCkPath, String ... topics){
        if (topics.length == 0) {
            throw new RuntimeException("传入的topic的个数为0, 你现在传了个得er");
        }


        System.setProperty("HADOOP_USER_NAME","atguigu");
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", port);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(parallelism);


        env.enableCheckpointing(5000);
        env.setStateBackend(new HashMapStateBackend());
        //env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop102:8020/gmall/" + groupIdAndCkPath);
        env.getCheckpointConfig().setCheckpointStorage(new JobManagerCheckpointStorage());

        env.getCheckpointConfig().setCheckpointTimeout(30000);
        env.getCheckpointConfig().setMaxConcurrentCheckpoints(1);
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(500);
        env.getCheckpointConfig().setExternalizedCheckpointCleanup(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);



        HashMap<String, DataStreamSource<String>> topicAndStreamMap = new HashMap<>();

        for (String topic : topics) {
            DataStreamSource<String> stream = env.addSource(FlinkSourceUtil.getKafkaSource(groupIdAndCkPath, topic));
            topicAndStreamMap.put(topic,stream);
        }
// 具体处理业务
        handle(env,topicAndStreamMap);

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
